package com.twu.biblioteca;

import java.io.*;
import java.util.ArrayList;

/**
 * Created by Binsabbar on 24/09/2014.
 *
 */
public class BookLoader extends BibliotecaLoader{

  private ArrayList<Book> bookLists;

  public BookLoader() {
    bookLists = new ArrayList<Book>(5);
  }

  public Book[] readBooksFromFile(String pathToFile, String fileName){
    try{
      BufferedReader fileReader = super.getFile(pathToFile, fileName);
      if (fileReader == null) return null;

      String line = fileReader.readLine();
      while(line != null){
        Book aBook = creatBookFromFileLine(line);
        if(aBook != null) bookLists.add(aBook);
        line = fileReader.readLine();
      }
      fileReader.close();
      if (bookLists.size() > 0) return bookLists.toArray(new Book[bookLists.size()]);
    }
    catch (IOException ignored){
      return null;
    }
    return null;
  }

  public Book creatBookFromFileLine(String line){
    String[] parsedLine = line.split(",");
    if (parsedLine.length != 4) return null;

    String [] bookComponents = new String[4];
    for (int i = 0; i < parsedLine.length; i++) {
      bookComponents[i] = parsedLine[i].trim();
      if (bookComponents[i].isEmpty()) return null;
    }

    int year;
    try{
      year = Integer.parseInt(bookComponents[3]);
    }
    catch (NumberFormatException e){
      return null;
    }

    Author author = new Author(bookComponents[1], bookComponents[2]);
    return new Book(bookComponents[0], author, year);
  }
}
